package com.igrowing.gateway;


import com.ApiBack.springbootinit.model.entity.InterfaceInfo;
import com.ApiBack.springbootinit.model.entity.User;
import com.ApiBack.springbootinit.service.InnerInterfaceInfoService;
import com.ApiBack.springbootinit.service.InnerUserInterfaceInfoService;
import com.ApiBack.springbootinit.service.InnerUserService;
import com.igrowing.utils.Encrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;


@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;
    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST=Arrays.asList("127.0.0.1");
    private static Map<String,String> nonceMap = new HashMap<>();
    private static final long FIFTEEN_MINUTES = 60 * 15L;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //todo:记录请求日志
        ServerHttpRequest request = exchange.getRequest();
        //请求的源地址
        String host = request.getLocalAddress().getHostString();
        String url = request.getURI().toString();
        log.info("请求url:" + url);
        log.info("请求地址:" + host);
        log.info("请求地址:" + request.getRemoteAddress().toString());
        //请求路径
        String path = request.getPath().value();
        log.info("请求路径:" + path);
        //请求方法
        String method = request.getMethod().toString();
        log.info("请求方法:" + method);
        //请求参数
        String queryParams = request.getQueryParams().toString();
        log.info("请求参数:" + queryParams);

        //todo：这里可以设置一些黑白名单，限制ip，防止遭到恶意攻击和刷量
        /*if (!IP_WHITE_LIST.contains(host))
        {
           return handleNoAuth(exchange.getResponse()) ;

        }*/

        //todo:用户权限校验
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String body = headers.getFirst("body");
        String key = headers.getFirst("Key");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        body = new String(body.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
      /*
      todo 防重放处理,使用redis的expire比较好，待优化。不过仅仅需要一个过期自动删除就引入redis有点使整个项目臃肿
      todo 所以，我们这里采用的是没过五分钟执行一次定时任务将保存时间超过十五分钟的nonce删除，以此来减轻服务器压力，释放一些资源
       */

        if (System.currentTimeMillis()/1000-Long.parseLong(timestamp)>FIFTEEN_MINUTES)
        {
            return handleNoAuth(exchange.getResponse());
        }
        if (nonceMap.containsKey(nonce))
        {
            return handleNoAuth(exchange.getResponse());
        }
        nonceMap.put(nonce, timestamp);



        //todo 为了防止报错，保护网关，这里查询时使用try-catch保护网关
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("抱歉，用户不存在",e);
        }

        if (invokeUser==null)
        {
            return handleNoAuth(exchange.getResponse()) ;
        }

        //todo 通过ak和sk校验用户身份是否合法
        String secretKey = invokeUser.getSecretKey();
        if (!key.equals(Encrypt.encrypt(body, secretKey)))
        {
            return handleNoAuth(exchange.getResponse()) ;
        }


        InterfaceInfo interfaceInfo=innerInterfaceInfoService.getInterfaceInfo(url, method);


        return handleResponse(exchange, chain, interfaceInfo.getId(), invokeUser.getId());
    }



    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = (HttpStatus) originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }



    @Override
    public int getOrder() {
        return -1;
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    public Mono<Void> handleNoFind(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return response.setComplete();
    }

    @Scheduled(fixedRate = 8 * 60 * 1000)
    public void removeNonce()
    {
        for (Map.Entry<String,String> entry : nonceMap.entrySet())
        {
            if (System.currentTimeMillis()/1000-Long.parseLong(entry.getValue())>FIFTEEN_MINUTES)
            {
                nonceMap.remove(entry.getKey());
            }
        }
    }

}